package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.config.UserContextHolder;
import com.hmall.order.constants.MqConstants;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderLogisticsService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
@Transactional
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderLogisticsService logisticsService;

    @Override
    public int findStatusById(Long orderId) {
        return orderMapper.findStatusById(orderId);
    }

    @Override
    public OrderDetail getOrderDetail(Long orderId) {
        return orderMapper.getOrderDetail(orderId);
    }

    @Override
    public int cancelOrder(Long orderId) {
        return orderMapper.cancelOrder(orderId);
    }

    @Override
    public String addOrder(RequestParams params) {
        //从上下文获取用户id
        String userID = UserContextHolder.holder.get();
        if (userID == null) {
            throw new RuntimeException("用户未登录，生成订单失败");
        }
        System.out.println("userID = " + userID);
        //通过openFeign调用item服务获取商品详情
        Item item = itemClient.getItemByid(params.getItemId() + "");
        Address address = userClient.findAddressById(Long.valueOf(params.getAddressId()));
        //计算总价
        Long totalFee = (item.getPrice() * params.getNum());

        Order order = new Order();
        OrderDetail orderDetail = new OrderDetail();
        OrderLogistics orderLogistics = new OrderLogistics();

        //封装order
        order.setStatus(1);
        order.setTotalFee(totalFee);
        order.setPaymentType(params.getPaymentType());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setUserId(Long.valueOf(userID));
        //将order存入数据库
        int insert = orderMapper.insert(order);

        //封装orderDetail
        orderDetail.setOrderId(order.getId());
        orderDetail.setItemId(Long.valueOf(params.getItemId()));
        orderDetail.setNum(params.getNum());
        orderDetail.setTitle(item.getName());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setImage(item.getImage());
        orderDetail.setCreateTime(new Date());
        orderDetail.setUpdateTime(new Date());
        //存入数据库
        orderDetailService.save(orderDetail);
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setPhone(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setCity(address.getCity());
        orderLogistics.setTown(address.getTown());
        orderLogistics.setStreet(address.getStreet());
        orderLogistics.setCreateTime(new Date());
        orderLogistics.setUpdateTime(new Date());
        //存数据库
        logisticsService.save(orderLogistics);
        //减库存
        itemClient.InventoryControl(item.getId().toString(), params.getNum());

        rabbitTemplate.convertAndSend(
                MqConstants.ORDER_EXCHANGE, MqConstants.ORDER_PAY_KEY, order.getId().toString()
                , message -> {
                    // 设置延迟毫秒值
                    message.getMessageProperties().setExpiration(String.valueOf(1000 * 60 * 15));
                    return message;
                }
        );
        System.out.println(order.getId());
//        List<String> list = new ArrayList<>();
//        list.add(order.getId().toString());
//        return list;
        //转换业务逻辑，修改前端，解决精度丢失重新返回字符串订单id
        return order.getId().toString();
    }

    @Override
    public int payisOk(Long orderId) {
        return orderMapper.payisOk(orderId);
    }
}
